package com.lgy.rabbit.controller;

import com.lgy.rabbit.mq.DemoRabbit;
import com.lgy.rabbit.mq.DlxBusinessRabbit;
import com.lgy.rabbit.mq.EmailTopicRabbit;
import com.lgy.rabbit.mq.OrderFanoutRabbit;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/myTest")
@RequiredArgsConstructor
public class DemoController {
    private final RabbitTemplate rabbitTemplate;


    /**
     * http://127.0.0.1:8080/myTest/testFanout
     * @return
     */
    @RequestMapping("/testFanout")
    public String testFanout(){
        String s = "{\"day\":\"2024-05-15\"}" + new Random().nextInt(100);
        rabbitTemplate.convertAndSend(OrderFanoutRabbit.DEMO_SEND_FANOUT.exchange(), "", s);
        return "test";
    }

    @RequestMapping("/testIndex")
    public String testIndex(){
        String s = "{\"day\":\"2024-05-15\"}" + new Random().nextInt(100);
        rabbitTemplate.convertAndSend(DemoRabbit.DEMO_SEND.exchange(), DemoRabbit.DEMO_SEND.routingKey(), s);
        return "test";
    }

    @RequestMapping("/testIndexTopic")
    public String testIndexTopic(){
        String s = "{\"day\":\"2024-05-15\"}" + new Random().nextInt(100);
        String routingKey = "email.123.topic";
        rabbitTemplate.convertAndSend(EmailTopicRabbit.EMAIL_TOPIC_RABBIT.exchange(), routingKey, s);
        return "test";
    }

    @RequestMapping("/testDlx")
    public String testDlx(){
        String s = "{\"day\":\""+ new Date() + "\"}" + new Random().nextInt(100);
        //rabbitTemplate.convertAndSend(DlxBusinessRabbit.USER_MESSAGE_NORMAL.exchange(), DlxBusinessRabbit.USER_MESSAGE_NORMAL.routingKey(), s);
        sendCustomDelayMessage(s, 1000 * 60);
        return s;
    }


    // 发送自定义延迟消息（毫秒）
    public void sendCustomDelayMessage(String message, int delayMillis) {
        System.out.println("发送消息：" + message);
        rabbitTemplate.convertAndSend(
            DlxBusinessRabbit.USER_MESSAGE_NORMAL.exchange(),
            DlxBusinessRabbit.USER_MESSAGE_NORMAL.routingKey(),
            message,
            msg -> {
                msg.getMessageProperties().setExpiration(String.valueOf(delayMillis));
                return msg;
            });
    }
}
